<template>
  <div class="main-box scroll">
    <!--    <TreeFilter label="name" :data="treeFilterData" @change="changeTreeFilter"> </TreeFilter>-->
    <div class="main-box-left">
      <el-tree
        class="tree"
        :data="treeFilterData"
        node-key="id"
        :current-node-key="1"
        :highlight-current="true"
        :props="defaultProps"
        default-expand-all
        @node-click="handleNodeClick"
      />
    </div>
    <div class="table-box">
      <ProTable
        v-if="curKey === 1"
        ref="proTable"
        title="综合运行管理平台"
        highlight-current-row
        :columns="sysColumns"
        :request-api="getLogTableList"
        :pagination="true"
        :show-summary="false"
        :init-param="initParam"
        :indent="20"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 4 }"
      >
        <template #verbose="scope">
          <span class="text">{{ scope.row.result.verbose }}</span>
        </template>
      </ProTable>
      <ProTable
        v-else-if="curKey === 2"
        ref="proTable"
        title="多云管理"
        highlight-current-row
        :columns="cloudColumns"
        :request-api="getCloudLogTableList"
        :pagination="true"
        :show-summary="false"
        :init-param="initParam"
        :indent="20"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 4 }"
      >
        <template #status="scope">
          <span class="text">{{ status[scope.row.status.toLowerCase()] }}</span>
        </template>
        <template #user_name="scope">
          <span class="text">{{
            (scope.row["user_name"] || "-") + (scope.row["user_id"] ? "(" + scope.row["user_id"] + ")" : "(-)")
          }}</span>
        </template>
        <template #created_at="scope">
          <span class="text">{{ moment(scope.row.created_at).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
        <template #operation="scope">
          <el-button type="primary" link @click="openDialog('detailRef', scope.row)"> 详情 </el-button>
        </template>
      </ProTable>
      <modalDetail ref="detailRef" />
    </div>
  </div>
</template>

<script setup lang="ts" name="userManagement">
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getTreeList, getLogList, getCloudLogList, getSearchConfig, getData } from "@/api/modules/sysManagement/logManagement";
import { onMounted, ref, reactive } from "vue";
import moment from "moment";
import modalDetail from "./component/modal_detail.vue";
// ProTable 实例
const proTable = ref<ProTableInstance>();
const status = ref<any>({
  success: "成功",
  error: "失败",
  running: "执行中"
});
// 表格配置项
let columns = ref<ColumnProps<any>[]>();
const sysColumns = ref<ColumnProps<any>[]>([
  { type: "index", label: "#", width: 80 },
  { prop: "create_at", label: "操作时间", width: 200 },
  { prop: "source", label: "日志模块", width: 120 },
  { prop: "detail", label: "详情", minWidth: 100 },
  { prop: "user", label: "操作人员", width: 120 },
  { prop: "verbose", label: "操作结果", width: 150 }
]);
const cloudColumns = ref<ColumnProps<any>[]>([
  { type: "index", label: "#", width: 80 },
  { prop: "operation_name", label: "任务", search: { el: "input", key: "operation_name__icontains" }, width: 200 },
  { prop: "object_name", label: "对象", search: { el: "input", key: "object_name__icontains" }, width: 120 },
  { prop: "object_uuid", label: "对象ID", minWidth: 100 },
  { prop: "status", label: "状态", width: 120 },
  { prop: "user_name", label: "操作人", search: { el: "input", key: "user_name__icontains" }, width: 150 },
  { prop: "res_org_path", label: "项目", search: { el: "input", label: "VDC/项目", key: "res_org_path__icontains" }, width: 150 },
  { prop: "ip_address", label: "访问IP", width: 150 },
  { prop: "operation_id", label: "任务类型ID", width: 150 },
  { prop: "request_id", label: "操作请求ID", width: 150 },
  {
    prop: "created_at",
    label: "操作时间",
    search: {
      el: "date-picker",
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      span: 2
    },
    width: 150
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 180 }
]);

columns.value = JSON.parse(JSON.stringify(sysColumns.value));
// 获取筛选项
const getSearchConfigData = async () => {
  const { data } = await getSearchConfig();
  // sysColumns.value.map(item => {
  //   const i = searchArr.find(a => a.key === item.prop);
  //   if (i) {
  //     setSearchDate(i, item);
  //   } else {
  //     sysColumns.value.push({
  //       prop: 1
  //     });
  //   }
  // });
  data.map(item => {
    const i = sysColumns.value.find(a => a.prop === item.key);
    if (i) {
      sysColumns.value.map(a => {
        if (a.prop === item.key) {
          a = setSearchDate(item, a);
        }
      });
    } else {
      let col = {
        prop: item.key,
        label: item.name,
        minWidth: 150,
        isShow: false
      };
      col = setSearchDate(item, col);
      sysColumns.value.push(col);
    }
  });
};
const setSearchDate = (i, item) => {
  switch (i.type) {
    case "datetimeRange":
      item["search"] = {
        el: "date-picker",
        props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
        span: 2,
        label: i.name
      };
      break;
    case "selectOne":
      if (!i.apiSearch) {
        item["search"] = { el: "select", label: i.name };
        const arr = i.data.map(item => {
          return {
            label: item[1],
            value: item[0]
          };
        });
        item["enum"] = arr;
      } else {
        item["search"] = { el: "select-v2", label: i.name };
        item["enum"] = async () => {
          const params = {};
          params[i.apiSearch.search_key] = "";
          const { data } = await getData(i.apiSearch.url, params);
          const arr = data.map(item => {
            return {
              label: item[i.apiSearch.value_field],
              value: item[i.apiSearch.key_field]
            };
          });
          return { data: arr };
        };
      }
      break;
    default:
      item["search"] = { el: i.type, label: i.name };
  }
  return item;
};
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
// 获取 treeFilter 数据
const defaultProps = {
  children: "child",
  label: "name"
};
const curKey = ref<any>(1);
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const { data } = await getTreeList();
  treeFilterData.value = [...data];
};
const getLogTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.create_at && (newParams.create_at_after = newParams.create_at[0]);
  newParams.create_at && (newParams.create_at_before = newParams.create_at[1]);
  delete newParams.create_at;
  // const params = {};
  return getLogList(newParams);
};
const getCloudLogTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.created_at && (newParams.startTime = newParams.created_at[0]);
  newParams.created_at && (newParams.endTime = newParams.created_at[1]);
  delete newParams.created_at;
  return getCloudLogList(newParams);
};
const handleNodeClick = (data: { [key: string]: any }) => {
  curKey.value = data.id;
};
// 多云管理查看详情
const detailRef = ref<InstanceType<typeof modalDetail> | null>(null);
const openDialog = (ref: string, data?: object) => {
  switch (ref) {
    case "detailRef":
      detailRef.value?.openDialog(data);
      break;
  }
};
onMounted(async () => {
  getTreeFilter();
  getSearchConfigData();
});
</script>

<style lang="scss" scoped>
@import "index";
</style>
